import datetime
import hashlib
import time

from django.test import TestCase

# Create your tests here.
"""
前后端分离模式下 为了区分用户的状态  不会在采用不分离模式下的cookie和session会话保持机制   解耦合 
jwt  json web token     token  字符串   自认证真伪 
str  xxxx.yyyy.zzzz
xxxx 头部  
{
  "alg": "HS256",
  "typ": "JWT"
}

Base64Url encoded   -> xxxx
yyyy 载荷  存储一些用户相关信息  uid  username  role  不要存储敏感信息  密码 
{
  "id": "1234567890",
  "name": "John Doe",
  "role": 'admin'
}
Base64Url encoded to form the second part of the JSON Web Token  -> yyyy
zzzz 签名
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)   secret  : 秘钥    ->  hash256('xxxx.yyyy',secret)  ->   zzzz

"""
#  python中集成jwt  pip install PyJWT
import jwt
# 生成token
def create_jwt():
    pay_load = {
        'id': 1,
        'username': 'xiaoming',
        'role': 'admin',
        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=5)  # utcnow()  否则时间不生效
    }
    secret = 'python2511'
    token = jwt.encode(pay_load, secret, algorithm='HS256')  # algorithm  签名的算法
    return token


# 校验token真伪
def verify_jwt(token):
    #  没有异常则校验通过
    result = jwt.decode(token, key="python2511", algorithms=['HS256'])
    return result


if __name__ == '__main__':
    token = create_jwt()
    # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ4aWFvbWluZyIsInJvbGUiOiJhZG1pbiJ9.W1UV1lbT1jy_XBTwMo1ql26LRkocIzyubszwGKLRmjY
    # token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ4aWFvbWluZyIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc0ODkzMjc0OH0.gwWNlgoF7ECvXvROOe8Q-oM8TwYuqhkQ_qgHN_woQR4'
    print(token)
    # time.sleep(7)
    # 校验token
    result = verify_jwt(token)  # ExpiredSignatureError
    print(result.get('id'))
    print(result.get('username'))
    print(result.get('role'))

    print(hashlib.md5('111111'.encode('utf-8')).hexdigest())
